package com.book.exception;

/**
 * @Author: 125715
 * @Package: com.book.exception
 * @Date: 2025/4/2 19:06
 * @Description: 异常处理类
 */

import com.book.dictionary.ResultCodeEnum;
import com.book.util.BaseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.List;
import java.util.Set;

/**
 * @description: 统一异常处理类
 * @Author yl
 * @Date 2024/3/13 9:45
 */
@ControllerAdvice
public class BusinessExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(BusinessExceptionHandler.class);

    /**
     * 自定义业务异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public BaseResult<String> handleBusinessException(BusinessException e) {
        logger.error("自定义异常信息：{}", e.getMessage(), e);
        return BaseResult.errorResult(e.getMessage());
    }

    /**
     * 参数校验异常，将校验失败的所有异常组合成一条错误信息
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public BaseResult<String> handleValidException(MethodArgumentNotValidException e) {
        logger.error("参数绑定校验异常：{}", e.getMessage());
        List<FieldError> fieldError = e.getBindingResult().getFieldErrors();
        StringBuilder sb = new StringBuilder();
        for (FieldError error : fieldError) {
            logger.info("error.getField:{}", error.getField());
            logger.info("defaultMessage:{}", error.getDefaultMessage());
            sb.append(error.getField() + error.getDefaultMessage() + ",");
        }
        String result = sb.substring(0, sb.length() - 1);
        logger.info("返回给前端的提示结果为：{}", result);
        return BaseResult.errorResult(result);
    }

    /**
     * 参数绑定异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public BaseResult<String> handleBindException(BindException e) {
        logger.error("参数绑定校验异常：{}", e.getMessage());

        return BaseResult.errorResult(e.getMessage());
    }

    /**
     * 参数异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseBody
    public BaseResult<String> handleConstraintViolationException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> cons = e.getConstraintViolations();
        StringBuilder sb = new StringBuilder();
        for (ConstraintViolation<?> con : cons) {
            Path path = con.getPropertyPath();
        }
        logger.error("handleConstraintViolationException参数绑定校验异常:{}", e.getLocalizedMessage());
        return BaseResult.errorResult(e.getLocalizedMessage());
    }

    /**
     * 参数类型不匹配常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public BaseResult<String> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        logger.error("参数类型不匹配异常:{}", e.getParameter());

        return BaseResult.errorResult(e.getMessage());
    }

    /**
     * 其他异常异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public BaseResult<String> handleRuntimeException(RuntimeException e) {
        logger.error("其他异常：{}", e);
        return BaseResult.errorResult(ResultCodeEnum.ERROR_RESULT_CODE);
    }
}
